﻿#if AVALONIA

using Avalonia.Interactivity;

#else

using System.Windows;

#endif

using KinonekoSoftware.Foundation;
using KinonekoSoftware.Foundation.UI.ViewModels;

namespace KinonekoSoftware.Platform.Controls
{
    public abstract class ForestUserControlBase : UserControl
    {
        protected ForestUserControlBase()
        {
            //
            // Event
            Loaded   += OnLoaded;
            Unloaded += OnUnloaded;
        }

        private void OnUnloaded(object sender, RoutedEventArgs e)
        {
            //
            //
            Loaded   -= OnLoaded;
            Unloaded -= OnUnloaded;

            //
            //
            OnUnloaded();
            OnUnloading();
        }
        
        
        
        private void OnViewModelStateCallbackImpl(object parameter)
        {
            //
            //
            OnViewModelMessaging(parameter);
        }

        internal virtual void OnUnloading()
        {
            //
            //
            var vm = ViewModel<ManagedLifetimeObject>();

            if (vm is not null)
            {
                vm.Suspend();
                
                if (vm is ViewModelBase fs)
                {
                    fs.ViewStateCallback = OnViewModelStateCallbackImpl;
                }
            }
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            
            //
            //
            var vm = ViewModel<ManagedLifetimeObject>();

            //
            //
            if (vm is not null)
            {
                if (vm.IsInitialized)
                {
                    vm.Resume();
                }
                else
                {
                    vm.Start();
                }
                
                if (vm is ViewModelBase fs)
                {
                    fs.ViewStateCallback = OnViewModelStateCallbackImpl;
                }
            }

            //
            //
            OnViewModelStateCallbackImpl(null);
            
            //
            //
            OnLoaded();
        }

        protected virtual void OnLoaded()
        {

        }

        protected virtual void OnUnloaded()
        {

        }


        protected virtual void OnViewModelMessaging(object parameter)
        {
            
        }
        
        protected T ViewModel<T>() where T : ManagedLifetimeObject
        {
            return DataContext as T;
        }
    }
    
    
#if AVALONIA && (IPAD || ANDROID || IOS)
    
    public abstract class TabbedWindow : UserControl
    {
        protected override void OnLoaded(RoutedEventArgs e)
        {
            if (Avalonia.Application.Current is ITopLevelProvider app)
            {
                app.TopLevel = TopLevel.GetTopLevel(this);
            }
            
            base.OnLoaded(e);
        }
    }
    
#endif
}